<template>
    <div class="app-container calendar-list-container">

        <!-- 查询和其他操作 -->
        <div class="filter-container">
          <el-input clearable class="filter-item" style="width: 200px;" placeholder="平台编号" v-model="listQuery.platformId"></el-input>
          <el-input clearable class="filter-item" style="width: 200px;" placeholder="活动名称" v-model="listQuery.activityName"></el-input>
          <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
          <el-button class="filter-item" type="primary" v-if="activity_btn_add" @click="handleCreate" icon="el-icon-plus">添加</el-button>
        </div>

        <!-- 查询结果 -->
        <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>
          <el-table-column align="center" min-width="150px" label="平台编号" prop="platformId">
          </el-table-column>   
          <el-table-column align="center" min-width="150px" label="活动名称" prop="activityName">
          </el-table-column>
          <el-table-column align="center" min-width="150px" label="活动摘要" prop="activityDes">
          </el-table-column>       
          <el-table-column align="center" min-width="200px" label="活动内容" prop="activityContent">
          </el-table-column>       
          <el-table-column align="center" min-width="100px" label="活动开始日期" prop="activityStartTime">
            <template slot-scope="scope">
              <span>{{scope.row.activityStartTime | formatDate1}}</span>
            </template>
          </el-table-column>   
          <el-table-column align="center" min-width="100px" label="活动结束日期" prop="activityEndTime">
            <template slot-scope="scope">
              <span>{{scope.row.activityEndTime | formatDate1}}</span>
            </template>
          </el-table-column>   
          <el-table-column align="center" min-width="200px" label="活动地点" prop="activityAddr">
          </el-table-column>   
          <el-table-column align="center" min-width="100px" label="活动类型" prop="acttypeName">
          </el-table-column>   
          <el-table-column align="center" min-width="80px" label="发起状态" prop="initiationStatus">
              <template slot-scope="scope">
                  <span v-if="scope.row.initiationStatus == 0">准备中</span>
                  <span v-if="scope.row.initiationStatus == 1">进行中</span>
                  <span v-if="scope.row.initiationStatus == 2">结束</span>
              </template>
          </el-table-column>   
          <el-table-column align="center" min-width="80px" label="人数限制" prop="peopleNum">
            <template slot-scope="scope">
              <span v-if="scope.row.peopleNum > 0">{{scope.row.peopleNum}}人</span>
              <span v-if="scope.row.peopleNum == 0">没有限制</span>
            </template>
          </el-table-column>   
          <el-table-column align="center" label="操作" width="150" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button  type="primary" size="mini" v-if="activity_btn_update"  @click="handleUpdate(scope.row)">编辑</el-button>
                <el-button  type="primary" size="mini" v-if="activity_btn_del" @click="handleDelete(scope.row)">删除</el-button>
              </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
            :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
        </div>

        <!-- 添加对话框 -->
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="dataForm.activityName" clearable=""></el-input>
            </el-form-item>
            <el-form-item label="活动logo" prop="activityLogo">
              <div  @click="upLogo">
                <img v-if="dataForm.activityLogo" :src="dataForm.activityLogo">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
              <input type="file" name="file" id="upload_logo" @change="uploadLogo" accept="image/png,image/gif" style="display: none">
            </el-form-item>      
            <el-form-item label="活动摘要" prop="activityDes">
              <el-input v-model="dataForm.activityDes" clearable=""></el-input>
            </el-form-item>
            <el-form-item label="活动内容" prop="activityContent">
              <el-input v-model="dataForm.activityContent" clearable=""></el-input>
            </el-form-item>
            <el-form-item label="开始时间" prop="activityStartTime">
              <el-date-picker  v-model="dataForm.activityStartTime" type="datetime" :picker-options="pickerStartDateBegin" format="yyyy-MM-dd HH:mm" placeholder="" clearable=""></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="activityEndTime">
              <el-date-picker v-model="dataForm.activityEndTime" type="datetime" :picker-options="pickerEndDateAfter" format="yyyy-MM-dd HH:mm" placeholder="" clearable=""></el-date-picker>
            </el-form-item>
            <el-form-item label="活动地点" prop="activityAddr">
              <el-input v-model="dataForm.activityAddr" clearable=""></el-input>
            </el-form-item>
            <el-form-item label="活动封面" prop="coverImg">
              <div  @click="upCover">
                <img v-if="dataForm.coverImg" :src="dataForm.coverImg">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
              <input type="file" name="file" id="upload_cover" @change="uploadCover" accept="image/png,image/gif" style="display: none">
            </el-form-item>
            <el-form-item label="二维码图片" prop="qrImg">
              <div  @click="upQrImg">
                <img v-if="dataForm.qrImg" :src="dataForm.qrImg">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
              <input type="file" name="file" id="upload_qr" @change="uploadQr" accept="image/png,image/gif" style="display: none">
            </el-form-item>      
            <el-form-item label="发布者姓名" prop="publisherName">
              <el-input v-model="dataForm.publisherName"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="publisherContactway">
              <el-select v-model="dataForm.publisherContactway" placeholder="请选择" clearable="">
                <el-option label="微信号" value="0">
                </el-option>
                <el-option label="QQ号" value="1">
                </el-option>
                <el-option label="手机号" value="2">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系号码" prop="publisherContactvalue">
              <el-input v-model="dataForm.publisherContactvalue" clearable=""></el-input>
            </el-form-item>  
            <el-form-item label="人数限制" prop="peopleNum"> 
              <el-input type="text" v-model="dataForm.peopleNum" clearable=""></el-input>
            </el-form-item>      
            <el-form-item label="活动类型" prop="acttypeStr"> 
              <el-select v-model="dataForm.acttypeStr" placeholder="请选择" clearable="">
                <el-option v-for="item in acttypes" :key="item.value" :label="item.label" :value="item.label+'&'+item.value"></el-option>
              </el-select>
            </el-form-item>               
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData('dataForm')">确定</el-button>
            <el-button v-if="dialogStatus == 'update'" type="primary" @click="updateData('dataForm')">确定</el-button>
          </div>
        </el-dialog>
    </div>
</template>

<script>
import waves from '@/directive/waves' // 水波纹指令
import { listActivity, addActivity, closeActivity, updateActivity, deleteActivity } from '@/api/cms/activity/index'
import { uploadImg } from '@/api/cms/society/index'
import { mapGetters } from 'vuex'
import { formatDate } from '@/utils/index'

export default {
  name: 'activity',
  directives: {
    waves
  },
  data() {
    return {
      listQuery: {
        page: 1,
        limit: 10,
        activityName: '',
        platformId: '',
        merchantId: ''
      },
      list: [],
      total: 0,
      listLoading: false,
      dialogFormVisible: false,
      downloadLoading: false,
      activity_btn_update: false,
      activity_btn_del: false,
      activity_btn_add: false,
      dataForm: {
        activityName: '',
        activityLogo: '',
        activityDes: '',
        activityContent: '',
        activityStartTime: undefined,
        activityEndTime: undefined,
        activityAddr: '',
        coverImg: '',
        qrImg: '',
        publisherName: '',
        publisherContactway: '',
        publisherContactvalue: '',
        acttypeName: '',
        initiationStatus: 0,
        peopleNum: 0,
        acttype: '',
        acttypeStr: '',
        merchantId: '',
        platformId: '',
        activityStartTimeStr: '',
        activityEndTimeStr: ''
      },
      textMap: {
        create: '创建',
        update: '编辑'
      },
      dialogStatus: '',
      rules: {
        activityName: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ],
        // activityLogo: [
        //   {
        //     required: true,
        //     message: '请上传活动logo',
        //     trigger: 'blur'
        //   }
        // ],
        activityDes: [
          {
            required: true,
            message: '请输入活动摘要',
            trigger: 'blur'
          }
        ],
        activityContent: [
          {
            required: true,
            message: '请输入活动介绍',
            trigger: 'blur'
          }
        ],
        activityStartTime: [
          {
            required: true,
            message: '请选择开始日期',
            trigger: 'blur'
          }
        ],
        activityEndTime: [
          {
            required: true,
            message: '请选择结束日期',
            trigger: 'blur'
          }
        ],
        activityAddr: [
          {
            required: true,
            message: '请输入活动地址',
            trigger: 'blur'
          }
        ],
        // coverImg: [
        //   {
        //     required: true,
        //     message: '请上传活动封面图',
        //     trigger: 'blur'
        //   }
        // ],
        // qrImg: [
        //   {
        //     required: true,
        //     message: '请上传活动封二维码',
        //     trigger: 'blur'
        //   }
        // ],
        publisherName: [
          {
            required: true,
            message: '请输入发布者姓名',
            trigger: 'blur'
          }
        ],
        publisherContactway: [
          {
            required: true,
            message: '请选择联系方式',
            trigger: 'blur'
          }
        ],
        publisherContactvalue: [
          {
            required: true,
            message: '请输入号码',
            trigger: 'blur'
          }
        ],
        acttypeStr: [
          {
            required: true,
            message: '请选择活动类型',
            trigger: 'blur'
          }
        ],
        peopleNum: [
          {
            required: true,
            message: '请输入限制人数',
            trigger: 'blur'
          },
          {
            pattern: /^[0-9]*$/,
            message: '输入格式错误，请重新输入!'
          }
        ]
      },
      acttypes: [
        {
          label: '运动',
          value: '1'
        },
        {
          label: '游戏',
          value: '2'
        },
        {
          label: '交友',
          value: '3'
        },
        {
          label: '旅行',
          value: '4'
        },
        {
          label: '读书',
          value: '5'
        },
        {
          label: '竞赛',
          value: '6'
        },
        {
          label: '电影',
          value: '7'
        },
        {
          label: '音乐',
          value: '8'
        },
        {
          label: '其他',
          value: '9'
        }],
      pickerStartDateBegin: {
        disabledDate: (time) => {
          return time.getTime() < (Date.now() - 24 * 60 * 60 * 1000)
        }
      },
      pickerEndDateAfter: {
        disabledDate: (time) => {
          return time.getTime() < this.dataForm.activityStartTime
        }
      }
    }
  },
  filters: {
    formatDate1(time) {
      var date = new Date(time)
      return formatDate(date, 'yyyy-MM-dd hh:mm')
    }
  },
  created() {
    this.getList()
    this.activity_btn_update = this.elements['activityManager:btn_update']
    this.activity_btn_del = this.elements['activityManager:btn_del']
    this.activity_btn_add = this.elements['activityManager:btn_add']
  },
  computed: {
    ...mapGetters([
      'elements',
      'name'
    ])
  },

  methods: {
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    getList() {
      this.listLoading = true
      this.listQuery.platformId = this.platformId
      listActivity(this.listQuery).then(response => {
        console.log(response)
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleUpdate(row) {
      this.dataForm = row
      this.dataForm.acttypeStr = row.acttypeName
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    updateData(formName) {
      var acttypeName = this.dataForm.acttypeStr.split('&')[0]
      var acttype = this.dataForm.acttypeStr.split('&')[1]
      this.dataForm.acttype = acttype
      this.dataForm.acttypeName = acttypeName
      this.dataForm.merchantId = this.merchantId
      this.dataForm.platformId = this.platformId

      var date1 = new Date(this.dataForm.activityStartTime)
      var date2 = new Date(this.dataForm.activityEndTime)
      var now = new Date()
      if (formatDate(now, 'yyyy-MM-dd HH:mm') === formatDate(date1, 'yyyy-MM-dd hh:mm')) {
        this.dataForm.initiationStatus = 1
      } else {
        this.dataForm.initiationStatus = 0
      }

      this.dataForm.activityStartTimeStr = formatDate(date1, 'yyyy-MM-dd hh:mm')
      this.dataForm.activityEndTimeStr = formatDate(date2, 'yyyy-MM-dd hh:mm')
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          this.listLoading = true
          updateActivity(this.dataForm).then(response => {
            if (response.success) {
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将删除选中项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteActivity(row)
            .then(response => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
        })
    },
    handleCreate() {
      this.resetForm()
      this.dataForm.platformId = this.platformId
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(formName) {
      var acttypeName = this.dataForm.acttypeStr.split('&')[0]
      var acttype = this.dataForm.acttypeStr.split('&')[1]
      this.dataForm.acttype = acttype
      this.dataForm.acttypeName = acttypeName
      this.dataForm.merchantId = this.merchantId
      this.dataForm.platformId = this.platformId

      var date1 = new Date(this.dataForm.activityStartTime)
      var date2 = new Date(this.dataForm.activityEndTime)
      var now = new Date()
      if (formatDate(now, 'yyyy-MM-dd HH:mm') === formatDate(date1, 'yyyy-MM-dd hh:mm')) {
        this.dataForm.initiationStatus = 1
      } else {
        this.dataForm.initiationStatus = 0
      }

      this.dataForm.activityStartTimeStr = formatDate(date1, 'yyyy-MM-dd hh:mm')
      this.dataForm.activityEndTimeStr = formatDate(date2, 'yyyy-MM-dd hh:mm')

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addActivity(this.dataForm).then(response => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDetail(row) {

    },
    handleClose(row) {
      this.$confirm('此操作将结束选中活动, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          closeActivity(row)
            .then(response => {
              console.log(response)
              if (response.success) {
                this.$notify({
                  title: '成功',
                  message: '操作成功',
                  type: 'success',
                  duration: 2000
                })
                this.getList()
              }
            })
        })
    },
    upCover: function() {
      document.getElementById('upload_cover').click()
    },
    uploadCover(event) {
      if (event.target.files.length > 0) {
        this.file = event.target.files[0] // 提交的图片
        console.log(this.file)
        const param = new FormData() // 创建form对象
        param.append('file', this.file)
        uploadImg(param).then(response => {
          if (response.success) {
            this.dataForm.coverImg = response.data.filePath
            alert('ok')
          }
        })
      }
    },
    upQrImg: function() {
      document.getElementById('upload_qr').click()
    },
    uploadQr(event) {
      if (event.target.files.length > 0) {
        this.file = event.target.files[0] // 提交的图片
        console.log(this.file)
        const param = new FormData() // 创建form对象
        param.append('file', this.file)
        uploadImg(param).then(response => {
          if (response.success) {
            this.dataForm.qrImg = response.data.filePath
          }
        })
      }
    },
    upLogo: function() {
      document.getElementById('upload_logo').click()
    },
    uploadLogo(event) {
      if (event.target.files.length > 0) {
        this.file = event.target.files[0] // 提交的图片
        console.log(this.file)
        const param = new FormData() // 创建form对象
        param.append('file', this.file)
        uploadImg(param).then(response => {
          if (response.success) {
            this.dataForm.activityLogo = response.data.filePath
            alert('ok')
          }
        })
      }
    },
    resetForm() {
      this.dataForm = {
        activityName: '',
        activityLogo: '',
        activityDes: '',
        activityContent: '',
        activityStartTime: undefined,
        activityEndTime: undefined,
        activityAddr: '',
        coverImg: '',
        qrImg: '',
        publisherName: '',
        publisherContactway: '',
        publisherContactvalue: '',
        acttypeName: '',
        initiationStatus: '',
        peopleNum: 0,
        acttype: '',
        acttypeStr: ''
      }
    }
  }
}
</script>

<style>

</style>


